<template>
  <div class="order-management">
    <!-- 操作栏 -->
    <div class="operation-bar">
      <el-input
        v-model="searchText"
        placeholder="搜索订单编号/用户姓名/手机号"
        style="width: 360px"
        clearable
      >
        <template #prefix>
          <el-icon><Search /></el-icon>
        </template>
      </el-input>
      <el-button type="success" @click="handleAdd">
        <el-icon><Plus /></el-icon>新建订单
      </el-button>
    </div>

    <!-- 数据表格 -->
    <el-table 
      :data="filteredOrders" 
      border 
      style="width: 100%"
      header-row-class-name="table-header"
      stripe
      highlight-current-row
    >
      <el-table-column prop="orderId" label="订单编号" width="180" sortable align="center" />
      <el-table-column prop="userName" label="用户姓名" width="120" />
      <el-table-column prop="phone" label="联系电话" width="150" />
      <el-table-column label="商品详情" width="220">
        <template #default="{ row }">
          <div v-for="item in row.items" :key="item.id">
            {{ item.name }} ×{{ item.quantity }}
          </div>
        </template>
      </el-table-column>
      <el-table-column prop="totalAmount" label="总金额" width="120" align="center">
        <template #default="{ row }">
          <span style="color: #f56c6c;">¥{{ row.totalAmount.toFixed(2) }}</span>
        </template>
      </el-table-column>
      <el-table-column prop="status" label="状态" width="120" align="center">
        <template #default="{ row }">
          <el-tag :type="statusTagType[row.status]" effect="light">
            {{ statusOptions.find(s => s.value === row.status)?.label }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="orderTime" label="下单时间" width="160" sortable />
      <el-table-column label="操作" width="180" fixed="right" align="center">
        <template #default="{ row }">
          <el-button size="small" type="primary" plain @click="handleEdit(row)">编辑</el-button>
          <el-button
            size="small"
            type="danger"
            plain
            @click="handleDelete(row.orderId)"
          >
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 添加/编辑对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="isEditMode ? '编辑订单信息' : '新建鲜花订单'"
      width="680"
    >
      <el-form
        ref="formRef"
        :model="formData"
        :rules="formRules"
        label-width="100px"
        label-position="left"
      >
        <el-form-item label="订单编号" prop="orderId">
          <el-input 
            v-model="formData.orderId" 
            :disabled="isEditMode"
            placeholder="ORD开头+8位日期+3位序列"
          />
        </el-form-item>
        <el-form-item label="用户姓名" prop="userName">
          <el-input v-model="formData.userName" placeholder="请输入收货人姓名"/>
        </el-form-item>
        <el-form-item label="联系电话" prop="phone">
          <el-input v-model="formData.phone" />
        </el-form-item>
        <el-form-item label="商品清单" prop="items">
          <el-select 
            v-model="formData.items"
            multiple
            style="width: 100%"
            placeholder="请选择鲜花商品"
          >
            <el-option
              v-for="item in flowerItems"
              :key="item.id"
              :label="item.name"
              :value="item"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="总金额" prop="totalAmount">
          <el-input-number
            v-model="formData.totalAmount"
            :min="0"
            :step="1"
            controls-position="right"
            style="width: 100%"
            :precision="2"
          />
        </el-form-item>
        <el-form-item label="订单状态" prop="status">
          <el-select v-model="formData.status" placeholder="请选择状态">
            <el-option
              v-for="item in statusOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="收货地址" prop="address">
          <el-input 
            v-model="formData.address"
            type="textarea"
            rows="2"
            placeholder="请输入详细收货地址"
          />
        </el-form-item>
        <el-form-item label="下单时间" prop="orderTime">
          <el-date-picker
            v-model="formData.orderTime"
            type="datetime"
            placeholder="选择下单时间"
            value-format="YYYY-MM-DD HH:mm:ss"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="success" @click="submitForm">确认</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, computed, reactive } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'

// 鲜花商品列表
const flowerItems = [
  { id: 1, name: '红玫瑰礼盒', price: 199 },
  { id: 2, name: '香槟玫瑰花束', price: 299 },
  { id: 3, name: '向日葵花篮', price: 159 },
  { id: 4, name: '郁金香花束', price: 228 },
  { id: 5, name: '满天星干花', price: 88 }
]

// 状态选项及样式
const statusOptions = [
  { value: 'pending', label: '待付款' },
  { value: 'paid', label: '已支付' },
  { value: 'shipped', label: '已发货' },
  { value: 'completed', label: '已完成' },
  { value: 'canceled', label: '已取消' }
]

const statusTagType = {
  'pending': 'warning',
  'paid': 'success',
  'shipped': '',
  'completed': 'info',
  'canceled': 'danger'
}

// 初始订单数据（10条）
const orders = ref([
  {
    orderId: 'ORD20240518001',
    userName: '张三',
    phone: '13800138000',
    items: [
      { id: 1, name: '红玫瑰礼盒', quantity: 2, price: 199 },
      { id: 5, name: '满天星干花', quantity: 1, price: 88 }
    ],
    totalAmount: 486,
    status: 'paid',
    address: '北京市朝阳区朝阳门街道1号',
    orderTime: '2024-05-18 09:23:15'
  },
  {
    orderId: 'ORD20240518002',
    userName: '李四',
    phone: '13900239001',
    items: [
      { id: 3, name: '向日葵花篮', quantity: 1, price: 159 }
    ],
    totalAmount: 159,
    status: 'shipped',
    address: '上海市浦东新区陆家嘴金融中心',
    orderTime: '2024-05-18 10:45:30'
  },
  {
    orderId: 'ORD20240518003',
    userName: '王芳',
    phone: '13600346002',
    items: [
      { id: 2, name: '香槟玫瑰花束', quantity: 3, price: 299 }
    ],
    totalAmount: 897,
    status: 'completed',
    address: '广州市天河区珠江新城',
    orderTime: '2024-05-18 11:15:22'
  },
  {
    orderId: 'ORD20240518004',
    userName: '陈伟',
    phone: '13500457003',
    items: [
      { id: 4, name: '郁金香花束', quantity: 2, price: 228 },
      { id: 5, name: '满天星干花', quantity: 2, price: 88 }
    ],
    totalAmount: 632,
    status: 'pending',
    address: '杭州市西湖区西溪湿地',
    orderTime: '2024-05-18 13:42:18'
  },
  {
    orderId: 'ORD20240518005',
    userName: '林娜',
    phone: '13700568004',
    items: [
      { id: 1, name: '红玫瑰礼盒', quantity: 1, price: 199 }
    ],
    totalAmount: 199,
    status: 'canceled',
    address: '深圳市福田区华强北',
    orderTime: '2024-05-18 14:30:45'
  },
  {
    orderId: 'ORD20240518006',
    userName: '黄强',
    phone: '13300679005',
    items: [
      { id: 2, name: '香槟玫瑰花束', quantity: 2, price: 299 },
      { id: 3, name: '向日葵花篮', quantity: 1, price: 159 }
    ],
    totalAmount: 757,
    status: 'paid',
    address: '成都市锦江区春熙路',
    orderTime: '2024-05-18 15:18:37'
  },
  {
    orderId: 'ORD20240518007',
    userName: '周敏',
    phone: '13100789006',
    items: [
      { id: 4, name: '郁金香花束', quantity: 3, price: 228 }
    ],
    totalAmount: 684,
    status: 'shipped',
    address: '武汉市江汉区中山大道',
    orderTime: '2024-05-18 16:05:29'
  },
  {
    orderId: 'ORD20240518008',
    userName: '徐杰',
    phone: '13000899007',
    items: [
      { id: 5, name: '满天星干花', quantity: 5, price: 88 }
    ],
    totalAmount: 440,
    status: 'completed',
    address: '南京市鼓楼区新街口',
    orderTime: '2024-05-18 17:22:11'
  },
  {
    orderId: 'ORD20240518009',
    userName: '吴婷',
    phone: '18900989008',
    items: [
      { id: 1, name: '红玫瑰礼盒', quantity: 1, price: 199 },
      { id: 2, name: '香槟玫瑰花束', quantity: 1, price: 299 }
    ],
    totalAmount: 498,
    status: 'paid',
    address: '西安市雁塔区大唐不夜城',
    orderTime: '2024-05-18 18:35:44'
  },
  {
    orderId: 'ORD20240518010',
    userName: '郑浩',
    phone: '18701009009',
    items: [
      { id: 3, name: '向日葵花篮', quantity: 2, price: 159 }
    ],
    totalAmount: 318,
    status: 'pending',
    address: '重庆市渝中区解放碑',
    orderTime: '2024-05-18 19:15:03'
  }
])

// 搜索功能
const searchText = ref('')
const filteredOrders = computed(() => {
  return orders.value.filter(order => {
    return Object.values(order).some(value => 
      String(value).toLowerCase().includes(searchText.value.toLowerCase())
  )})
})

// 对话框相关状态
const dialogVisible = ref(false)
const isEditMode = ref(false)
const formRef = ref(null)
const formData = reactive({
  orderId: '',
  userName: '',
  phone: '',
  items: [],
  totalAmount: 0,
  status: 'pending',
  address: '',
  orderTime: new Date().toISOString().split('T')[0].replace('T', ' ') + ' 00:00:00'
})

// 表单验证规则
const formRules = {
  orderId: [
    { required: true, message: '请输入订单编号', trigger: 'blur' },
    { pattern: /^ORD\d{8}\d{3}$/, message: '格式要求：ORD+8位日期+3位序列', trigger: 'blur' }
  ],
  userName: [{ required: true, message: '请输入用户姓名', trigger: 'blur' }],
  phone: [
    { required: true, message: '请输入联系电话', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '请输入有效手机号码', trigger: 'blur' }
  ],
  items: [{ required: true, message: '请至少选择一个商品', trigger: 'change' }],
  address: [{ required: true, message: '请输入收货地址', trigger: 'blur' }],
  orderTime: [{ required: true, message: '请选择下单时间', trigger: 'change' }],
  status: [{ required: true, message: '请选择订单状态', trigger: 'change' }]
}

// 操作函数
const handleAdd = () => {
  isEditMode.value = false
  resetForm()
  dialogVisible.value = true
}

const handleEdit = (row) => {
  isEditMode.value = true
  Object.assign(formData, { ...row })
  dialogVisible.value = true
}

const handleDelete = (orderId) => {
  ElMessageBox.confirm('确定要删除该鲜花订单吗？', '警告', {
    confirmButtonText: '确认',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    orders.value = orders.value.filter(u => u.orderId !== orderId)
    ElMessage.success('删除成功')
  })
}

const submitForm = async () => {
  await formRef.value.validate()
  if (isEditMode.value) {
    const index = orders.value.findIndex(u => u.orderId === formData.orderId)
    orders.value.splice(index, 1, { ...formData })
  } else {
    if (orders.value.some(u => u.orderId === formData.orderId)) {
      return ElMessage.warning('订单编号已存在')
    }
    orders.value.push({ ...formData })
  }
  dialogVisible.value = false
  ElMessage.success(isEditMode.value ? '修改成功' : '添加成功')
}

const resetForm = () => {
  formData.orderId = ''
  formData.userName = ''
  formData.phone = ''
  formData.items = []
  formData.totalAmount = 0
  formData.status = 'pending'
  formData.address = ''
  formData.orderTime = new Date().toISOString().split('T')[0].replace('T', ' ') + ' 00:00:00'
}
</script>

<style scoped lang="scss">
.order-management {
  padding: 24px;
  background: #f8fafc;
  min-height: 100vh;

  .operation-bar {
    padding: 16px 24px;
    background: #fff;
    border-radius: 8px;
    box-shadow: 0 2px 8px rgba(28, 36, 56, 0.08);
    margin-bottom: 24px;
    display: flex;
    align-items: center;
    gap: 16px;
  }

  :deep(.table-header) th {
    background-color: #f8fafc !important;
    color: #64748b;
    font-weight: 600;
    height: 56px;
  }

  .el-table {
    border-radius: 8px;
    overflow: hidden;
    box-shadow: 0 2px 8px rgba(28, 36, 56, 0.08);
    
    .el-tag {
      font-size: 13px;
      padding: 0 8px;
      height: 26px;
      line-height: 24px;
    }
  }
}

.el-dialog {
  border-radius: 12px;
  
  .el-dialog__header {
    border-bottom: 1px solid #e2e8f0;
    margin: 0 24px;
    padding: 24px 0 16px;
  }
  
  .el-dialog__body {
    padding: 24px 32px;
  }
  
  .el-dialog__footer {
    border-top: 1px solid #e2e8f0;
    padding: 16px 24px;
  }
}

.el-form-item {
  margin-bottom: 20px;
}
</style>